'''
健康随e保重疾保障计划（儿童版）
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import execjs
from common.helper import Helper
class Spider( object ):

    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "健康随e保重疾保障计划（儿童版）"
    # 生产产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["20年", "25年"],
                # 保额
                "money": ["100000", "200000", "300000", "400000"],
                # 缴费间隔 0 一次缴清
                "interval": ["0", "3", "5", "10"],
                # 缴费方式
                "payType":["月缴","年缴"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["30年", "70岁"],
                # 保额
                "money": ["100000", "200000", "300000", "400000"],
                # 缴费间隔 0 一次缴清
                "interval": ["0", "3", "5", "10","20"],
                # 缴费方式
                "payType": ["月缴", "年缴"]

            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["80岁", "终身"],
                # 保额
                "money": ["100000", "200000", "300000", "400000"],
                # 缴费间隔 0 一次缴清
                "interval": ["0", "3", "5", "10","20","至60岁"],
                # 缴费方式
                "payType": ["月缴", "年缴"]

            }

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["expire"],plan[k]["money"],plan[k]["interval"],plan[k]["payType"]):

                #写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4],v[5]
                ) )

    #计算保费
    def calcPremium(self,dt=None):

        if "年" in dt["expire"]:

            expire = dt["expire"].replace("年","")

        elif "岁" in dt["expire"]:

            expire = dt["expire"].replace("岁","a")

        else:

            expire = "106a"


        if dt["interval"] == "0":

            interval = "1"

            data = {
                "year":dt["year"],
                "gender":"1" if dt["gender"] == "M" else "2",
                "money":str( int(int(dt["money"])/10000)),
                "expire":expire,
                "interval":interval ,
                "payType":"12",
            }
        else:

            data = {
                "year": dt["year"],
                "gender": "1" if dt["gender"] == "M" else "2",
                "money": str(int(int(dt["money"]) / 10000)),
                "expire": expire,
                "interval": dt["interval"] if "岁" not in dt["interval"] else "60a",
                "payType": "12",
            }

        js = open("./"+self.name+".js",mode='r',encoding="utf-8").read()

        cxt = execjs.compile( js )

        try:

            result = cxt.call("calcPremium",data)

            if dt["payType"] == "年缴":
                print("~~~~~~~~~~~~年缴~~~~~~~~~~~~")
                price = Helper.decimalParse( result["year_price"])

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )


            else:
                print("~~~~~~~~~~~~月缴~~~~~~~~~~~~")
                price = Helper.decimalParse(result["month_price"])

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                self.mysql.updatePrice(data)

        except Exception as e:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("/*更新产品价格失败:%s*/"%dt["id"])

    def main(self):

        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.calcPremium(dt)

